/*
 * @Author: LBH 1336709799@qq.com
 * @Date: 2023-05-20 11:03:20
 * @LastEditors: LBH 1336709799@qq.com
 * @LastEditTime: 2024-11-30 16:04:01
 * @FilePath: \heima-hr\src\store\modules\user.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { getProfile, login } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {},
    routes: constantRoutes
  },
  mutations: {
    setToken(state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    setRoutes(state, newRoutes) {
      state.routes = [...constantRoutes, ...newRoutes]
    }
  },
  actions: {
    async login(context, data) {
      console.log(data)
      const token = await login(data)
      context.commit('setToken', token)
    },
    async getUserInfo(context) {
      const result = await getProfile()
      context.commit('setUserInfo', result)
      return result
    },
    // 退出登录的action
    logout(context) {
      context.commit('removeToken') // 删除token
      context.commit('setUserInfo', {}) // 设置用户信息为空对象
      resetRouter() // 重置路由
    }
  }
}
